import index from "../views/userPage/Layout/index"
import VueRouter from "vue-router";
import Vue from "vue";

import store from "../store"

Vue.use(VueRouter);
// 解决报错
// const originalPush = VueRouter.prototype.push
// const originalReplace = VueRouter.prototype.replace
// // push
// VueRouter.prototype.push = function push(location, onResolve, onReject) {
//     if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
//     return originalPush.call(this, location).catch(err => err)
// }
// // replace
// VueRouter.prototype.replace = function push(location, onResolve, onReject) {
//     if (onResolve || onReject) return originalReplace.call(this, location, onResolve, onReject)
//     return originalReplace.call(this, location).catch(err => err)
// }
const router = new VueRouter({
    routes: [
        {
            path: '/',
            name: 'index',
            component: index,
            children: []
        },
        {
            path: "/login",
            name: 'login',
            component: () => import("@/views/Login.vue")
        }
    ]
})


// 白名单
const whiteList = ["/login"]
router.beforeEach((to, form, next) => {

    if (whiteList.includes(to.path)) {
        next()
    } else {
        store.dispatch("userStore/GetUserInfo").then(r => {
            if (r) {
                next()
            } else {
                next("/login")
            }
        }).catch(err => {
            console.error(err)
            next("/login")
        })
    }

})

router.afterEach((to) => {
    // if (to.matched.length === 0) {
    //     console.log(to)
    //     if (store.state.userStore.routes.some(route => '/' + route.path === to.path)) {
    //         router.replace(to.path)
    //     }
    // }
    router.replace(to.path).catch(()=>{
        console.log("路由内部错误")
    })
})


export default router;